<template>
  <!-- 文章列表 -->
  <div class="article-list">
    <!-- 刷新组件 -->
    <van-pull-refresh v-model="isreFreshLoading"
      :success-text="refreshSuccessText" :success-duration="1500"
      @refresh="onRefresh">
      <!-- /刷新组件 -->
      <van-list v-model="loading" :finished='findshed' findshed-text='没有更多了'
        @load='onLoad' :error.sync='error' error-text='请求失败，点击重新加载'>
        <!-- 文章列表组件 -->
        <ArticleItem v-for="(article, index) in list" :key="index"
          :article="article" />

      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  // 组件名称
  name: 'ArticleList',
  // 局部注册的组件
  components: {
    ArticleItem
  },
  // 组件参数 接收来自父组件的数据
  props: {
    channel: {
      type: Object,
      erquired: true
    }
  },
  // 组件状态值
  data () {
    return {
      list: [],
      loading: false,
      error: false,
      findshed: false,
      timestamp: null,
      // 下拉刷新的状态
      isreFreshLoading: false,
      refreshSuccessText: '刷新成功'
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
  */
  created () { },
  /**
  * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
  */
  mounted () { },
  // 组件方法
  methods: {
    async onLoad () {
      console.log('onLoad')
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        console.log(data)
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        console.log('请求出错了', err)
        this.loading = false
        this.error = true
      }
      setTimeout(() => {
        // 模拟数据加载
        // for (var i = 0; i < 10; i++) {
        //   this.list.push(this.list.length + 1)
        // }
        this.loading = false
        if (this.list.length >= 40) {
          this.finished = true
        }
      }, 1000)
    },
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.list.unshift(...results)
        this.isreFreshLoading = false
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        this.refreshSuccessText = '刷新失败'
        this.isreFreshLoading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  position: fixed;
  top: 180px;
  bottom: 100px;
  overflow-y: auto;
  right: 0;
  left: 0;
}
</style>
